package com.smartao.core.info.server;

import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.smartao.core.exceptions.SmartaoException;

public abstract class AppServer {

	protected String serverInfo;
	protected Properties props;
	protected InitialContext context;

	protected static final Logger logger = LoggerFactory.getLogger(AppServer.class);

	public AppServer(Properties props) {
		this.props = props;
		this.context = getCtx();
	}

	/**
	 * @param JndiName
	 * @return 容器对应的JndiName
	 */
	public abstract String getJndiName(String jndiName);

	/**
	 * @param props
	 * @return InitialContext
	 */
	public InitialContext getCtx() {
		try {
			return new InitialContext(props);
		} catch (NamingException ex) {
			logger.error("InitialContext Exception: may be you used wrong property name or value !" + ex);
			return null;
		}
	}

	/**
	 * 查找JNDI对象
	 * @param jndiBinding
	 * @return
	 */
	public Object lookup(String jndiBinding) {
		logger.info("Lookup JNDI:{}", jndiBinding);
		try {
			return context.lookup(getJndiName(jndiBinding));
		} catch (Exception ex) {
			throw new SmartaoException("JNDI look up Exception: jndi name '" + jndiBinding + "' not found!" + ex);
		}
	}

	/**
	 * @return 容器对应的TransactionManagerLookup类名
	 */
	public abstract String getTransactionManagerName();
	
	/**
	 * @return 获取服务器主目录
	 */
	public abstract String getServerHomeDir();
	
	/**
	 * @return 获取服务器临时目录
	 */
	public String getServerTempDir() {
		return System.getProperty("java.io.tmpdir");
	}

	@Override
	public String toString() {
		return serverInfo;
	}

	public String getServerInfo() {
		return serverInfo;
	}

	public void setServerInfo(String serverInfo) {
		this.serverInfo = serverInfo;
	}

}